from flask import Flask, render_template, request, session, redirect, url_for, flash

app = Flask(__name__)
app.secret_key = 'your_secret_key'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':

        username = request.form.get('username')
        password = request.form.get('password')

        session['username'] = username

        return redirect(url_for('home'))
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        confirm_password = request.form.get('confirm_password')

        errors = []
        if not (3 <= len(username) <= 12):
            errors.append('用户名长度应为 3-12 个字符')
        if not password:
            errors.append('密码不能为空')
        if password != confirm_password:
            errors.append('两次密码不一致')

        if not errors:

            session['username'] = username
            return redirect(url_for('home'))
        else:
            for error in errors:
                flash(error, 'error')
    return render_template('register.html')

@app.route('/')
def home():
    return render_template('home.html')

@app.route('/logout')
def logout():
    session.pop('username',None)

    return redirect(url_for('home'))

if __name__ == '__main__':
    app.run(debug=True)